package com.gitee.bluebird;

import io.netty.buffer.ByteBuf;

/**
 * * @createtime : 2018/11/26 8:14 PM
 **/
public class Packet {
    private short code;
    private byte[] body;

    private static final byte[] EMPTY_BODY = new byte[0];

    public Packet() {
    }

    public Packet(ByteBuf byteBuf) {
        this.code = byteBuf.readShort();
        int len = byteBuf.readableBytes();
        if (len == 0) {
            body = EMPTY_BODY;
        } else {
            body = new byte[len];
            byteBuf.readBytes(body);
        }
    }

    public Packet(short code, byte[] body) {
        this.code = code;
        this.body = body;
    }

    public Packet(short code) {
        this(code, EMPTY_BODY);
    }

    public void encode(ByteBuf byteBuf) {
        byteBuf.writeInt(body.length + 2).writeShort(code).writeBytes(body);
    }

    public short getCode() {
        return code;
    }

    public byte[] getBody() {
        return body;
    }
}
